import React, { useState, useEffect } from 'react';
import {reload, update} from './cmd';
import {DlgVal} from './ctl';
import {DlgMove} from 'sui/field/ctl';
import {Title, Ret, no_del, loc, WaitUmd, useCmd, is_empty, obj_str, MCmd, PanelTitle,
    useHigh, Btn, GridTable} from 'sui';

const RuleView = ({ cur, title, mod, hreturn }) => {
    const [main, setMain] = useState();
    const [open_val, openVal] = useState(false);
    const [open_move, openMove] = useState(false);
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => reload(null, cur, setMain), [cur]);

    const hSwap = (val) => {
        const fin = umd.fin;
        const ret = [...main];

        let pos = 0;

        const f = ret.find((d, i) => {
            pos = i;
            return d.index === fin.cur;
        });

        if (!f) {
            return;
        }

        if (val.tp === "up") {
            if (pos === 0) {
                return;
            }

            const a = ret[pos - 1];
            const b = ret[pos];

            ret[pos - 1] = b;
            ret[pos] = a;
        } else if (val.tp === "down") {
            if (pos === ret.length - 1) {
                return;
            }

            const a = ret[pos];
            const b = ret[pos + 1];

            ret[pos] = b;
            ret[pos + 1] = a;
        }

        ret.forEach((d, i) => d["index"] = i + 1);

        update(umd, cur, ret, setMain);
    };

    const hAdd = (val) => {
        const fin = umd.fin;
        const ret = [];

        if (is_empty(main)) {
            ret.push(val);
        }
        else {
            main.forEach(d => {
                ret.push(d);

                if (d.index === fin.cur) {
                    ret.push(val)
                }
            });
        }

        ret.forEach((d, i) => d["index"] = i + 1);

        update(umd, cur, ret, setMain);
    };

    const hEdit = (val) => {
        const fin = umd.fin;
        const ret = [];

        main.forEach(d => {
            if (d.index === fin.cur) {
                ret.push(val)
                return;
            }

            ret.push(d);
        });

        ret.forEach((d, i) => d["index"] = i + 1);

        update(umd, cur, ret, setMain);
    };

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        const index = val.index;
        const ret = [];

        main.forEach(d => {
            if (d.index === index) {
                return;
            }

            ret.push(d);
        });

        ret.forEach((d, i) => d["index"] = i + 1);

        update(umd, cur, ret, setMain);
    };

    const hAction = (d, tp) => {
        const index = d ? d.index : 0;

        umd.setFin({tp: tp, cur: index});

        if (tp === "add") {
            umd.setCur({ tp: "string", opt: "N" });
            openVal(true);
        } else if (tp === "edit") {
            umd.setCur(d);
            openVal(true);
        } else if (tp === "swap") {
            umd.setCur(d);
            openMove(true);
        }
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_238"), key: 'e_opt', width: 200, formatter: (props) => {
            const d = props.row;

            return (
                <div className="inline-flex">
                    <MCmd itype="add" hcmd={() => hAction(d, "add")}/>
                    <MCmd itype="edit" hcmd={() => hAction(d, "edit")}/>
                    <MCmd itype="swap" hcmd={() => hAction(d, "swap")}/>
                    <MCmd itype="del" hcmd={() => hDel(d)}/>
                </div>
            );
        }},
        {name: loc("l_229"), key: 'utype', width: 200},
        {name: loc("l_228"), key: 'name', width: 300},
        {name: loc("l_644"), key: 'num', width: 100},
        {name: loc("l_645"), key: 'value', width: 600},
    ];

    const hval = (val) => {
        const fin = umd.fin;

        if (fin.tp === "add") {
            hAdd(val);
        } else if (fin.tp === "edit") {
            hEdit(val);
        } else if (fin.tp === "swap") {
            hSwap(val);
        }
    };

    const Right = () => {
        const getAdd = () => {
            if (is_empty(main)) {
                return <Btn hcmd={() => hAction(null, "add")} className="mr-3">{loc("l_239")}</Btn>;
            }

            return null;
        };

        return (
            <div className="inline-flex">
                {getAdd()}
                <Ret hcmd={hreturn}/>
            </div>
        );
    };

    const Left = () => <Title mod={`${obj_str(cur, "sn")} ( ${obj_str(cur, "name")} )`} sub={loc("l_236")}/>;

    return (
        <div className="flex flex-col">
            <PanelTitle left={<Left/>} cl="green" right={<Right/>}/>
            <GridTable high={high} col={col} row={main} rowHeight={42}/>
            <DlgVal open={open_val} hcmd={hval} setOpen={openVal} data={umd.cur}/>
            <DlgMove open={open_move} hcmd={hval} setOpen={openMove} data={umd.cur}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {RuleView};
